<?php
class User_credit extends CS_Controller 
{
    private $log_type = array(
        1 => '消费',
        2 => '供应商授信',
        3 => '分销商发起授信',
    );
    public function _init() 
    {
        $this->load->library('pagination');
        $this->load->model('user_model','user');
        $this->load->model('user_credit_model','user_credit');
        $this->load->model('user_credit_log_model','user_credit_log');
    }
    
    public function grid($pg = 1)
    {
        $page_num = 15;
        $num = ($pg - 1) * $page_num;
        $getData = $this->input->post();
        $getData['provider_id'] = $this->uid;
        $config['first_url'] = site_url('user_credit/grid').$this->pageGetParam($this->input->post());
        $config['base_url'] = site_url('user_credit/grid');
        $config['suffix'] = $this->pageGetParam($this->input->post());
        $config['total_rows'] = $this->user_credit->findByCount($getData);
        $config['uri_segment'] = 3;
        $this->pagination->initialize($config);
        $data['pg_link'] = $this->pagination->create_links();
        $data['list'] = $this->user_credit->pageList($page_num, $num, $getData);
        $data['all_rows'] = $config['total_rows'];
        $data['pg_now'] = $pg;
        $data['pg_num'] = $page_num;
        $this->load->view('user_credit/grid', $data);
    }
    
    public function add()
    {
        $this->load->view('user_credit/add');
    }
    
    public function addPost()
    {
        $getData = $this->input->post();
        if (empty($getData['uid'])){
            $this->ajaxJson(['status' => false, 'msg' => '必须填写未授信的正确用户名或手机号']);
        }
        $result = $this->user->findOne(['uid' => $getData['uid']]);
        if ($result->num_rows() <= 0){
            $this->ajaxJson(['status' => false, 'msg' => '用户不存在']);
        }
        $type = $result->row()->user_type;
        if ($type & UTID_PROVIDER) {
            $this->ajaxJson(['status' => false, 'msg' => '用户不能为供应商']);
        }
        if (empty($getData['amount']) || !is_numeric($getData['amount'])){
            $this->ajaxJson(['status' => false, 'msg' => '授信金额必填,且为数字']);
        }
        if (!in_array($getData['status'], [0,1])){
            $this->ajaxJson(['status' => false, 'msg' => '状态参数异常']);
        }
        $getData['pay_money'] = $getData['amount'];
        $getData['provider_id'] = $this->uid;
        $getData['created_at'] = date('Y-m-d H:i:s');
        $logData = array(
            'type' => 2,
            'money' => $getData['amount'],
            'note' => $getData['note']?:'',
            'created_at' => date('Y-m-d H:i:s'),
        );
        unset($getData['note']);
        
        $this->db->trans_start();
        $creditId = $this->user_credit->insert($getData);
        if ($creditId){
            $logData['credit_id'] = $creditId;
            $creditLogId = $this->user_credit_log->insert($logData);
        }
        $this->db->trans_complete();
        
        if ($this->db->trans_status() === FALSE) {
            $this->ajaxJson(['status' => false, 'msg' => '添加失败']);
        }else {
            $this->ajaxJson(true, site_url('user_credit/grid'));
        }
    }
    
    public function appendCredit($id)
    {
        $result = $this->user_credit->findOne(['id' => $id, 'provider_id' => $this->uid]);
        if ($result->num_rows() <= 0){
            $this->ajaxJson(['status' => false, 'msg' => '该条记录异常']);
        }
        $credit = $result->row();
        $res = $this->user->findOne(['uid' => $credit->uid]);
        if ($res->num_rows() <= 0){
            $this->ajaxJson(['status' => false, 'msg' => '被授信用户信息异常']);
        }
        $data['user_name'] = $res->row()->user_name;
        $data['mobile_phone'] = $res->row()->mobile_phone;
        $data['id'] = $id;
        $data['nowamount'] = $credit->amount;
        $data['pay_money'] = $credit->pay_money;
        $this->load->view('user_credit/appendCredit',$data);
    }
    
    public function appendPost()
    {
        $getData = $this->input->post();
        $result = $this->user_credit->findOne(['id' => $getData['id'], 'provider_id' => $this->uid]);
        if ($result->num_rows() <= 0){
            $this->ajaxJson(['status' => false, 'msg' => '数据错误']);
        }
        $user_credit = $result->row();
        if (empty($getData['amount']) || !is_numeric($getData['amount'])){
            $this->ajaxJson(['status' => false, 'msg' => '授信金额必填,且为数字']);
        }
        $logData = array(
            'type'       => 2,
            'money'      => $getData['amount'],
            'note'       => $getData['note']?:'',
            'created_at' => date('Y-m-d H:i:s'),
            'credit_id'  => $user_credit->id,
        );
        $amount = $getData['amount'];
        $getData['amount'] = bcadd($amount, $user_credit->amount);
        $getData['pay_money'] = bcadd($amount, $user_credit->pay_money);
        $getData['updated_at'] = date('Y-m-d H:i:s');
        unset($getData['note']);
        
        $this->db->trans_start();
        $state = $this->user_credit->update($getData,['id' => $user_credit->id]);
        $creditLogId = $this->user_credit_log->insert($logData);
        $this->db->trans_complete();
        
        if ($this->db->trans_status() === FALSE) {
            $this->ajaxJson(['status' => false, 'msg' => '追加授信失败']);
        }else {
            $this->ajaxJson(true, site_url('user_credit/grid'));
        }
    }
    
    public function detail($id, $pg = 1)
    {
        $page_num = 15;
        $num = ($pg - 1) * $page_num;
        $getData = $this->input->post();
        $getData['credit_id'] = $id;
        $res = $this->user_credit->findOne(['id' => $id, 'provider_id' => $this->uid]);
        if ($res->num_rows() <= 0){
            $getData['credit_id'] = -100;
        }
        $config['first_url'] = site_url('user_credit/detail').$this->pageGetParam($this->input->post());
        $config['base_url'] = site_url('user_credit/detail');
        $config['suffix'] = $this->pageGetParam($this->input->post());
        $config['total_rows'] = $this->user_credit_log->findByCount($getData);
        $config['uri_segment'] = 3;
        $this->pagination->initialize($config);
        $data['pg_link'] = $this->pagination->create_links();
        $data['list'] = $this->user_credit_log->findPageList($num, $page_num, $getData, '*', 'id DESC');
        $user = $this->user->findOne(['uid' => $res->row()->uid])->row();
        $data['user_name'] = $user->user_name;
        $data['mobile_phone'] = $user->mobile_phone;
        $data['all_rows'] = $config['total_rows'];
        $data['pg_now'] = $pg;
        $data['pg_num'] = $page_num;
        $data['log_type'] = $this->log_type;
        $this->load->view('user_credit/detail',$data);
    }
    
    public function upOrDown($id, $state)
    {
        $result = $this->user_credit->findOne(['id' => $id, 'provider_id' => $this->uid]);
        if ($result->num_rows() <= 0){
            $this->error('user_credit/grid', '', '数据不存在');
        }
        if (!in_array($state, [0,1])){
            $this->error('user_credit/grid', '', '参数异常');
        }
        $is_suc = $this->user_credit->update(['status' => $state], ['id' => $id]);
        if (!$is_suc){
            $this->error('user_credit/grid', '', '更新操作失败');
        }else {
            switch ($state) {
                case 0:
                    $this->success('user_credit/grid', '', '禁用成功');
                    break;
                case 1:
                    $this->success('user_credit/grid', '', '启用成功');
                    break;
                    
                default:
                    ;
                    break;
            }
        }
    }
    
    public function ajaxQueryId()
    {
        $namephone = $this->input->post('namephone');
        if (valid_mobile($namephone)) {
            $res = $this->user->findOne(['mobile_phone' => $namephone]);
            if ($res->num_rows() != 1) {
                $this->ajaxJson(['status' => false, 'msg' => '用户不存在或存在多条']);
            }
        } else {
            $res = $this->user->findOne(['user_name' => $namephone]);
            if ($res->num_rows() != 1) {
                $this->ajaxJson(['status' => false, 'msg' => '用户不存在或存在多条']);
            }
        }
        $type = $res->row()->user_type;
        if ($type & UTID_PROVIDER) {
            $this->ajaxJson(['status' => false, 'msg' => '用户不能为供应商']);
        }
        $uid = $res->row()->uid;
        $count = $this->user_credit->findOne(['uid' => $uid, 'provider_id' => $this->uid])->num_rows();
        if ($count > 0) {
            $this->ajaxJson(['status' => false, 'msg' => '该用户已授信，请在授信管理列表中进行追加授信']);
        }
        $this->ajaxJson(true,'',['uid' => $uid]);
    }
}